package View;

import check.BoxRenderer;
import check.CheckBoxEditor;
import check.CheckBoxRenderer;
import customerview.BuyBook;
import customerview.MyOrder;
import customerview.ShoppingCart;
import customerview.UsersView;
import managerview.EditBook;
import users.ManagerFun;
import users.UsersFun;
import utils.Utils;

import javax.swing.event.CellEditorListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.table.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

//商城界面
public class View extends JFrame{
    String username;
    String token;
    public View(String username){
        this.username=username;
        try{
            Connection connection= Utils.getConnection();
            //定义sql语句
            String sql="select token from user where username = ?";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.setString(1,username);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                this.token = rs.getString("token");
            }
        }catch (Exception e){

        }
        //初始化界面
        initJFrame();
        //在这个界面添加内容
        initView();
        //让页面展示出来
        this.setVisible(true);

    }

    private void initView() {



        //添加搜索输入框
        JTextField searchText = new JTextField("（请输入图书编号）", 10);
        searchText.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (searchText.getText().equals("（请输入图书编号）")) {
                    searchText.setText(""); // 清空文本框供用户输入
                }
            }
            @Override
            public void focusLost(FocusEvent e) {
                if (searchText.getText().isEmpty()) {
                    searchText.setText("（请输入图书编号）"); // 用户未输入内容时恢复提示信息
                }
            }
        });
        searchText.setBounds(30,10,130,30);
        this.getContentPane().add(searchText);

        // 创建一个3行3列的默认数据模型
        DefaultTableModel model = new DefaultTableModel();

        // 如果需要可以给表格添加列名
        model.setColumnIdentifiers(new String[]{"选择","id", "书名", "类型","出版社","作者","单价","购买数量"});

        // 创建一个JTable实例并应用模型
        JTable table = new JTable(model) {
            // 重写isCellEditable方法，使所有单元格默认不可编辑，但"EditableColumn2"列的单元格可编辑
            @Override
            public boolean isCellEditable(int row, int column) {
                // 假设我们想要"EditableColumn2"列的单元格可编辑
                // 注意：列索引是从0开始的，所以"EditableColumn2"的索引是1
                return column == 7 ||column==0; // 允许第2列（索引为1）的单元格可编辑
            }
        };
        BoxRenderer centeredRenderer = new BoxRenderer();
        for (int i = 1; i < table.getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setCellRenderer(centeredRenderer);
        }
        // 可选：使用自定义渲染器或编辑器，例如复选框
        table.getColumnModel().getColumn(0).setCellRenderer(new CheckBoxRenderer());
        table.getColumnModel().getColumn(0).setCellEditor(new CheckBoxEditor((new JCheckBox())));

        try{
            //获取所有图书信息
            Connection connection= Utils.getConnection();
            //定义sql语句
            String sql="select * from book where num!=0";
            PreparedStatement stmt = connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while(rs.next()){
                int id_2 = rs.getInt("id");
                String name = rs.getString("name");
                String type = rs.getString("type");
                String publish = rs.getString("publish");
                String author = rs.getString("author");
                Double price = rs.getDouble("price");

                model.addRow(new Object[]{Boolean.FALSE,id_2,name,type,publish,author,price,1});
            }
            Utils.Close(stmt,connection);
        }catch (Exception e){

        }

        //多行复选框只能选一个，想使用就取消注释
//        table.addMouseListener(new MouseAdapter() {
//            @Override
//            public void mouseClicked(MouseEvent e) {
//                int row = table.rowAtPoint(e.getPoint());
//                for (int i = 0; i < model.getRowCount(); i++) {
//                    model.setValueAt(false, i, 0); // 先取消所有行的选中
//                }
//                model.setValueAt(true, row, 0); // 选中当前行
//
//            }
//        });
        // 使用JScrollPane包装表格以自动处理滚动条
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(20, 50, 760, 350); // 设置滚动面板的位置和大小
        this.getContentPane().add(scrollPane); // 将滚动面板添加到窗体的内容窗格中
        //添加查询按钮
        JButton searchButton=new JButton();
        searchButton.setBounds(186,9,80,30);
        searchButton.setText("查询");
        this.getContentPane().add(searchButton);
        searchButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try{
                    ManagerFun.queryone_2(searchText.getText(),model);
                }catch(Exception ex){
                    throw new RuntimeException(ex);

                    //JOptionPane.showMessageDialog(null,"查找失败","警告",JOptionPane.WARNING_MESSAGE);

                }
            }
        });

        // 添加监听代码...

        //添加前往购物车按钮
        JButton goToCarButton=new JButton();
        goToCarButton.setBounds(60,420,100,30);
        goToCarButton.setText("前往购物车");
        this.getContentPane().add(goToCarButton);
        //添加监听
        //.....
        goToCarButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                View.this.setVisible(false);
                new ShoppingCart(username);
            }
        });
        //添加直接购买按钮
        JButton purchaseButton=new JButton();
        purchaseButton.setBounds(330,420,100,30);
        purchaseButton.setText("直接购买");
        this.getContentPane().add(purchaseButton);
        //添加监听
        //.....
        purchaseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    UsersFun.purchase(table,username);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        //添加加入购物车按钮
        JButton joinCarButton=new JButton();
        joinCarButton.setBounds(580,420,100,30);
        joinCarButton.setText("加入购物车");
        this.getContentPane().add(joinCarButton);

        JButton book_manage = new JButton();
        book_manage.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                View.this.setVisible(false);
                new EditBook(username);
            }
        });
        book_manage.setText("管理图书");
        book_manage.setBounds(330, 9, 110, 30);

        getContentPane().add(book_manage);

        JButton myOrder = new JButton();
        myOrder.setText("我的订单");
        myOrder.setBounds(650, 9, 110, 30);
        getContentPane().add(myOrder);
        myOrder.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                View.this.setVisible(false);
                new MyOrder(username);
            }
        });

        JButton check = new JButton();
        check.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        check.setText("管理员审核");
        check.setBounds(495, 9, 110, 30);
        getContentPane().add(check);
        //添加监听
        //.....
        joinCarButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    UsersFun.addcart(table,username);
                    JOptionPane.showMessageDialog(null,"已添加至购物车！","消息提示",JOptionPane.PLAIN_MESSAGE);	//消息对话框
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        if (!token.equals("1")){
            book_manage.setVisible(false);
            check.setVisible(false);
        }
        if (token.equals("-1")){
            book_manage.setVisible(false);
            check.setVisible(false);
            joinCarButton.setVisible(false);
            myOrder.setVisible(false);
            purchaseButton.setVisible(false);
            goToCarButton.setVisible(false);
            
        }


    }

    private void initJFrame() {
        this.setTitle("GUET购书系统");
        this.setSize(800, 500);
        //设置页面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //取消按钮等元素居中放置
        getContentPane().setLayout(null);
    }
}
